package cn.itcast.music.ui.history;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import cn.itcast.music.R;
import cn.itcast.music.entity.Music;
import cn.itcast.music.entity.MusicHistory;
import cn.itcast.music.ui.history.MusicHistoryAdapter.ViewHolder;
import cn.itcast.music.ui.listen.ListenActivity;
import cn.itcast.music.util.DateTimeUtil;
import cn.itcast.music.util.MusicUtil;
import java.util.List;

public class MusicHistoryAdapter extends Adapter<ViewHolder> {

    private final List<MusicHistory> musicHistories;

    private final HistoryActivity activity;

    public MusicHistoryAdapter(List<MusicHistory> musicHistories,
            HistoryActivity activity) {
        this.musicHistories = musicHistories;
        this.activity = activity;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent,
            int viewType) {
        View view = View.inflate(parent.getContext(), R.layout.item_song_simple,
                null);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.tvIndex.setText(String.valueOf(position + 1));
        Music music = musicHistories.get(position).getMusic();
        holder.tvTitle.setText(music.getTitle());
        holder.tvPlayTime.setText(musicHistories.get(position).getDateTime());
        holder.tvArtist.setText(music.getArtist());
        holder.tvDuration.setText(
                DateTimeUtil.formatTime(music.getDuration()));

        holder.itemView.setOnClickListener(view -> {
            Log.d("App-PlayingHistoriesAdapter", "用户点击音乐！" + music);
            // 跳转到播放界面
            Intent intent = new Intent(activity, ListenActivity.class);
            // 这里的 position 是历史记录列表的 position，应该查找音乐的真实 position
            intent.putExtra("position", MusicUtil.positionInMusicList(music));
            activity.startActivity(intent);
            activity.finish();
        });
    }

    @Override
    public int getItemCount() {
        return musicHistories.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        TextView tvIndex;

        TextView tvTitle;

        TextView tvPlayTime;

        TextView tvArtist;

        TextView tvDuration;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvIndex = itemView.findViewById(R.id.tv_index);
            tvTitle = itemView.findViewById(R.id.tv_title);
            tvPlayTime = itemView.findViewById(R.id.tv_play_time);
            tvArtist = itemView.findViewById(R.id.tv_artist);
            tvDuration = itemView.findViewById(R.id.tv_duration);
        }

    }

}
